package com.example.secondhandspringboot.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.secondhandspringboot.context.BaseContext;
import com.example.secondhandspringboot.domain.entity.ChatMessages;
import com.example.secondhandspringboot.domain.entity.Contacts;
import com.example.secondhandspringboot.domain.entity.User;
import com.example.secondhandspringboot.domain.vo.ContactVO;
import com.example.secondhandspringboot.mapper.ChatMessagesMapper;
import com.example.secondhandspringboot.mapper.ContactsMapper;
import com.example.secondhandspringboot.service.IChatMessagesService;
import com.example.secondhandspringboot.service.IContactsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.secondhandspringboot.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.binding.BindingException;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 周在林
 * @since 2024-05-16
 */
@Service
@RequiredArgsConstructor
public class ContactsServiceImpl extends ServiceImpl<ContactsMapper, Contacts> implements IContactsService {

    private final ChatMessagesMapper chatMessagesMapper;
    private final ContactsMapper contactsMapper;

    /**
     * 获取联系人列表
     * @return
     */
    @Override
    public List<ContactVO> getContactsVOList() {
        // 获取当前用户id
        Long currentUserId = BaseContext.getCurrentId();
        // 查询联系人列表
        List<Contacts> contactsList = this.lambdaQuery().eq(Contacts::getUserId, currentUserId).list();
        List<ContactVO> contactVOList = new ArrayList<>();
        for (Contacts contact : contactsList) {
            ContactVO contactVO = new ContactVO();
            Session session = WebSocketServer.sessionPool.get(contact.getContactUserId());
            contactVO.setOnline(!(session == null));

            contactVO.setContactUserId(contact.getContactUserId());
            //获取当前联系人
            User user = Db.lambdaQuery(User.class).eq(User::getId, contact.getContactUserId()).one();
            contactVO.setContactUserName(user.getUsername());
            contactVO.setUserPic(user.getUserPic());

            // 获取与当前联系人最新消息
            ChatMessages chatMessages = chatMessagesMapper.lastNewMsg(currentUserId,contact.getContactUserId());
            if (chatMessages != null){
                contactVO.setNewContent(chatMessages.getMessageContent());
                contactVO.setNewMsgTime(chatMessages.getCreateTime());

                // 获取与当前联系人未读消息数量
                int num;
                try{
                    num = chatMessagesMapper.getUnReadNum(currentUserId,contact.getContactUserId());
                }catch (BindingException e){
                    num = 0;
                }
                contactVO.setNoticeNum(num);
            }
            contactVOList.add(contactVO);
        }
        //跟据最新消息事件排序
//        contactVOList.sort(Comparator.nullsFirst(Comparator.comparing(ContactVO::getNewMsgTime)));
        Comparator<ContactVO> comparator = Comparator
                .comparing(mapOrDefault(ContactVO::getNewMsgTime)).reversed();
        return contactVOList.stream().sorted(comparator).toList();
    }

    /**
     * 根据发送和接收者id获取联系人
     * @param currentUserId
     * @param contactUserId
     */
    @Override
    public Contacts getContactBySendAndReceiveId(Long currentUserId, Long contactUserId) {
        return contactsMapper.getContacts(currentUserId,contactUserId);
    }

    private Function<ContactVO, LocalDateTime> mapOrDefault(Function<ContactVO, LocalDateTime> func) {
        return vo -> Optional.ofNullable(func.apply(vo))
                .orElse(LocalDateTime.of(9999, 1, 1, 0, 0)); // 当newMsgTime为空时，设置默认的日期时间，如公元9999年1月1日0点0分
    }

}

